import {
  ModalForm,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Col, Image, message, Popconfirm, Row, Space } from 'antd';
import { openDB } from 'idb';
import { useRef, useState } from 'react';
import AddAndEdit from './components/addAndEdit';

// 初始化 IndexedDB
const dbPromise = openDB('ImageStorage', 1, {
  upgrade(db) {
    db.createObjectStore('dataSource');
  },
});

const TableList = () => {
  const formRef = useRef();
  const actionRef = useRef();

  const [open, setOpen] = useState(false);
  const [importOpen, setImportOpen] = useState(false);
  const [dataSource, setDataSource] = useState([]);
  const [dataSourceImport, setDataSourceImport] = useState([]);
  const [record, setRecord] = useState({});
  const [isEdit, setIsEdit] = useState(false);
  const [fileList, setFileList] = useState([]);

  const loadFilesFromCache = async () => {
    const db = await dbPromise;
    const cachedFiles = await db.getAll('dataSource');
    return cachedFiles;
  };

  const columns = [
    {
      hideInSearch: true,
      title: '序号',
      align: 'center',
      dataIndex: 'index',
      width: 100,
      render: (text, record, index) => index + 1,
    },
    {
      hideInSearch: true,
      title: 'ID',
      align: 'center',
      dataIndex: 'id',
      width: 200,
      ellipsis: true,
    },
    {
      title: '名称',
      align: 'center',
      dataIndex: 'title',
    },
    {
      hideInSearch: true,
      title: '描述',
      dataIndex: 'dec',
      align: 'center',
      valueType: 'text',
      width: 300,
      ellipsis: true,
    },
    {
      hideInSearch: true,
      title: '图片地址',
      dataIndex: 'url',
      align: 'center',
      render: (text, record) => {
        return (
          (record.url || record.link) && (
            <Image width={80} src={record.url || record.link} />
          )
        );
      },
    },
    {
      title: '操作',
      align: 'center',
      width: 200,
      dataIndex: 'option',
      valueType: 'option',
      render: (text, record) => (
        <Space>
          <Button
            type="link"
            onClick={() => {
              setOpen(true);
              setIsEdit(true);
              setRecord(record);
            }}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            onClick={() => {
              handleDelete(record.id);
            }}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  const handleDelete = async (id) => {
    const db = await dbPromise;
    await db.delete('dataSource', id);
    actionRef?.current?.reload();
    message.success('删除成功');
  };

  function parseJsonToArray(jsonString) {
    try {
      const array = JSON.parse(jsonString);
      if (Array.isArray(array)) {
        return array;
      } else {
        return []; // 返回空数组作为错误处理
        throw new Error('解析结果不是数组');
      }
    } catch (error) {
      console.error('JSON 解析错误:', error);
      return []; // 返回空数组作为错误处理
    }
  }

  const exportJsonToExcel = (data) => {
    const blob = new Blob([data], { type: 'text/plain;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = '导出的文件.txt';
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div>
      <ProTable
        headerTitle="图片文件"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
          defaultCollapsed: false,
        }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
        }}
        request={async (params) => {
          let array = await loadFilesFromCache();
          console.log(5555555, array);
          if (params.title) {
            array = array.filter((item) => item.title.includes(params.title));
            setDataSource(array);
          } else {
            setDataSource(array);
          }
          return {
            data: array,
            total: array.length,
            success: true,
          };
        }}
        toolBarRender={() => [
          <Button
            key="add"
            type="primary"
            onClick={() => {
              setOpen(true);
              setIsEdit(false);
              setRecord({});
            }}
          >
            新建
          </Button>,
          <Popconfirm
            key="delete"
            title="确认删除所有内容吗？"
            onConfirm={async () => {
              const db = await dbPromise;
              const transaction = db.transaction('dataSource', 'readwrite');
              const store = transaction.objectStore('dataSource');
              // 清空对象存储
              await store.clear();
              setDataSource([]);
              message.success('全部删除成功');
              actionRef?.current?.reload();
            }}
            okText="是"
            cancelText="否"
          >
            <Button key="3" type="primary" danger onClick={async () => {}}>
              删除所有内容
            </Button>
          </Popconfirm>,
        ]}
        columns={columns}
      />

      <AddAndEdit
        open={open}
        setOpen={setOpen}
        record={record}
        isEdit={isEdit}
        setDataSource={setDataSource}
        dataSource={dataSource}
        callback={() => {
          actionRef?.current?.reload();
        }}
      />

      <ModalForm
        width={1000}
        formRef={formRef}
        open={importOpen}
        modalProps={{
          destroyOnClose: true,
          forceRender: true,
          onCancel: () => {
            setImportOpen(false);
            setDataSourceImport('');
          },
        }}
        title={'导入内容'}
        onOpenChange={setImportOpen}
        style={{ paddingTop: 20 }}
        onFinish={async (value) => {
          // setImportOpen(false)
          let array = parseJsonToArray(value.content);
          let flag = true;
          if (array.length === 0) {
            message.error('请输入正确的格式');
            return;
          }
          array.forEach((item) => {
            if (!item.title) {
              message.error('标题不能为空');
              flag = false;
              return;
            }
            if (!item.dec) {
              message.error('描述不能为空');
              flag = false;
              return;
            }
            if (!item.url) {
              message.error('图片地址不能为空');
              flag = false;
              return;
            }
          });
          if (!flag) {
            message.error('请检查数据');
            return;
          }
          setDataSource(array);
          localStorage.setItem('dataSource', JSON.stringify(array));
          setImportOpen(false);
          message.success('导入成功');
          actionRef?.current?.reload();
        }}
      >
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}
        >
          <Button
            key="3"
            type="primary"
            style={{ marginBottom: 20 }}
            onClick={async () => {
              let tmp = formRef?.current?.getFieldValue('content');
              setDataSourceImport(tmp);
            }}
          >
            一键美化
          </Button>
          <div style={{ color: 'red', fontSize: 14 }}>
            注意：导入成功后立即生效，以前的内容会被覆盖
          </div>
        </div>
        <Row style={{ maxHeight: 500, overflowY: 'auto' }}>
          <Col span={12}>
            <ProFormTextArea
              name="content"
              label="输入要导入的内容"
              fieldProps={{
                autoSize: { minRows: 10 },
              }}
              placeholder="请输入导入的内容"
              rules={[
                { required: true, message: '导入的内容是必填项' },
                {
                  pattern: /^\S+(\s+\S+)*$/,
                  message: '不能以空格开始或结束',
                },
              ]}
            />
          </Col>
          <Col span={1}></Col>
          <Col span={11}>
            <ProFormTextArea
              name="contentBeautiful"
              value={dataSourceImport}
              label="美化后的内容"
              disabled
              fieldProps={{
                autoSize: { minRows: 10 },
              }}
            />
          </Col>
        </Row>
      </ModalForm>
    </div>
  );
};

export default TableList;
